package be.myandroid.games;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.util.Log;

public class StateManager {
	public enum State {MENU,PAUSE,RUNNING,FAILED,WON};
	private static String TAG = "StateManager";
	private State state = State.MENU;
	private static StateManager instance;
	private ArrayList<stateListener> listeners = new ArrayList<stateListener>();
	public Game currentGame;
	
	private StateManager(){
		
	}
	
	public void isChanged(){
		for (stateListener listener : listeners) {
			listener.isChanged(state);
		}
	}
	public interface stateListener{
		public void isChanged(State newState);
	}
	
	public static StateManager getInstance(){
		if(instance!=null)
			return instance;
		instance = new StateManager();
		return instance;
	}
	
	public State getState() {
		return state;
	}
	
	private void setState(State newState){
		state = newState;
		isChanged();
	}
	
	public void TogglePauze(){
		if(state == State.RUNNING) {
			Log.d(TAG,"Game Paused");
			setState(State.PAUSE);
		} else if(state == State.PAUSE) {
			Log.d(TAG,"Continue Game");
			setState(State.RUNNING);
		}
	}

	public boolean Paused() {
		return state == State.PAUSE;
	}

	public boolean Menu() {
		return state == State.MENU;
	}
	
	public boolean Running(){
		return state == State.RUNNING;
	}

	public void setOutcome(boolean b) {
		if(state == State.RUNNING) {
			if(b) {
				setState(State.WON);
				Log.d(TAG,"GAME WON");
			}
			else {
				setState(State.FAILED);
				Log.d(TAG,"GAME LOST");
			}
		}
		TimerTask task = new TimerTask(){
			@Override
			public void run() {
				gameStop();
		}};
		(new Timer()).schedule(task, 2000);
	}

	public void addListener(stateListener listener) {
		listeners.add(listener);
	}

	public void gameStart() {
		Log.d(TAG,"Hide Menu");
		setState(State.RUNNING);
	}
	
	public void gameStop() {
		Log.d(TAG,"Show Menu");
		setState(State.MENU);
	}

	public boolean Failed() {
		return state == State.FAILED;
	}

	public boolean Won() {
		return state == State.WON;
	}
}
